package common.server.feign;

import feign.Contract;
import feign.Logger;
import feign.Request;
import feign.Retryer;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.ConfigurableEnvironment;
import java.util.concurrent.TimeUnit;

/**
 * @Title: FeignClientDefaultConfiguration
 * @ProjectName com-bigwavn-group
 * @Description: Feign 客户端默认配置
 * @author: wangweitao 1749343503@qq.com
 * @date: 2019/6/4 16:11
 * @version: V1.0.0
 */
public class FeignClientDefaultConfiguration {

	/**
	 * 日志
	 */
	private static final org.slf4j.Logger logger = LoggerFactory
			.getLogger(FeignClientDefaultConfiguration.class);

	/**
	 * 默认http 链接超时时间
	 */
	private static final int HTTP_CONN_TIMEOUT = 6000;

	/**
	 * 默认http 读超时时间
	 */
	private static final int HTTP_READ_TIMEOUT = 15000;

	/**
	 *
	 * @return
	 */
	@Bean
	public Contract feignContract() {
		logger.debug(
				"========================初始化feign.Contract==========================");
		// 这将SpringMvc Contract 替换为feign.Contract.Default
		return new Contract.Default();
	}

	/**
	 * 构建HttpClient
	 *
	 * @return
	 */

	/**
	 *
	 * @return
	 */
	@Bean
	Logger.Level feignLoggerLevel() {
		return Logger.Level.FULL;
	}

	/**
	 * 重试机制，不重试
	 * 
	 * @return
	 */
	@Bean
	public Retryer feignRetryer() {
		return Retryer.NEVER_RETRY;
	}

	@Bean
	public Request.Options options(ConfigurableEnvironment env) {
		int readTimeout = env.getProperty("feign.readTimeout", int.class,
				HTTP_READ_TIMEOUT);
		int connTimeout = env.getProperty("feign.connectTimeout", int.class,
				HTTP_CONN_TIMEOUT);
		logger.info(
				"====================初始化Request.Options:conntimeout:{},readtimeout:{}======================",
				connTimeout, readTimeout);

		return new Request.Options(connTimeout, readTimeout);
	}

	@Bean
	public BaseRequestInterceptor basicRequestInterceptor() {
		logger.debug(
				"========================初始化RequestInterceptor==========================");
		return new BaseRequestInterceptor();
	}

	@Bean
	public DefaultErrorDecoder errorDecoder() {
		logger.debug(
				"========================初始化ErrorDecoder==========================");
		return new DefaultErrorDecoder();
	}
}
